package com.xr.sunnyday.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xr.sunnyday.constant.MessageConstant;
import com.xr.sunnyday.entity.Result;
import com.xr.sunnyday.pojo.OrderSetting;
import com.xr.sunnyday.service.OrdersettingService;
import com.xr.sunnyday.utils.POIUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/ordersetting")
public class OrdersettingController {

    @Reference
    private OrdersettingService ordersettingService;

    @PostMapping("/upload")
    public Result upload(MultipartFile excelFile){

        try {
            //读取要导入的excel文件
            List<String[]> excelString  = POIUtils.readExcel(excelFile);
            //创一个添加ordersetting集合
            List<OrderSetting> orderSettingList = new ArrayList<OrderSetting>();
            //将string转化成date类型的工具 调用poiutils的DATE_FORMAT方法
            SimpleDateFormat sdf = new SimpleDateFormat(POIUtils.DATE_FORMAT);

            Date parse = null;
            OrderSetting orderSetting = null;
            //将读取的文件List<String[]>转成List<OrderSetting>
            for (String[] dataArr: excelString) {
                //格式化每一行的第1个单元格：String->Data
                parse = sdf.parse(dataArr[0]);
                //格式化每一行的第2个单元格：String->int
                int number = Integer.valueOf(dataArr[1]);
                //创建orderSetting,将转化后的值添加
                 orderSetting = new OrderSetting(parse, number);
                 orderSettingList.add(orderSetting);
            }
            //调用服务（service的add方法）
            ordersettingService.add(orderSettingList);
            return new Result(true, MessageConstant.IMPORT_ORDERSETTING_SUCCESS);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false,MessageConstant.IMPORT_ORDERSETTING_FAIL);
    }

    @GetMapping("/getOrderSettingByMonth")
    public Result getOrderSettingByMonth(String month){
        List<Map<String,Integer>> data = ordersettingService.getOrderSettingByMonth(month);
        return new Result(true,MessageConstant.GET_ORDERSETTING_SUCCESS,data);
    }

    @PostMapping("/editNumberByDate")
    public Result editNumberByDate(@RequestBody OrderSetting orderSetting){
        ordersettingService.editNumberByDate(orderSetting);
        return new Result(true,MessageConstant.ORDERSETTING_SUCCESS);
    }
}
